﻿using System;
using System.Collections.Generic;
using System.Drawing.Imaging;
using System.IO;
using System.Linq;
using System.Threading.Tasks;
using Ace;
using Ace.Application.Common;
using Ace.Application.Wiki;
using Ace.Entity.Wiki;
using Ace.IdStrategy;
using Ace.Web.Mvc;
using Ace.Web.Mvc.Authorization;
using Ace.Web.Mvc.Models;
using Chloe.Admin.Common;
using Chloe.Admin.Common.Tree;
using Microsoft.AspNetCore.Mvc;
using OfficeOpenXml;

namespace Chloe.Admin.Areas.Wiki.Controllers
{

    [Area(AreaNames.Wiki)]
    [Permission("wiki.ckcate")]
    public class CKCateController : WebController<ICKCateService>
    {
        public IActionResult Index()
        {
            int ShopID = 0;
            IPro_SortService SortService = this.CreateService<IPro_SortService>();
            List<Pro_Sort> ListDistrict = SortService.GetList("", "", ShopID);
            ViewBag.SortList = ListDistrict;
             

            IBrandService brandService = this.CreateService<IBrandService>();
            List<Brand> ListBrand = brandService.GetList(0, "");
            ViewBag.BrandList = ListBrand;

            return View();
        }

        public ActionResult Models(Pagination pagination, int IsExplort, string CateID,string Code)
        { 
            PagedData<CKCate> pagedData = this.Service.GetPageData(pagination, IsExplort, CateID, Code);
            return this.SuccessData(pagedData);
        }


        [Permission("wiki.ckcate.delete")]
        [HttpPost]
        public ActionResult Delete(string id)
        { 
            this.Service.Delete(id);
            return this.SuccessMsg("删除成功");
        }

       
        [Permission("wiki.ckcate.edit")]
        [HttpPost]
        public ActionResult Edit(UpdateCKCateInput modle)
        {            
            this.Service.Update(modle);
            return this.SuccessMsg("编辑成功");
        }

        [Permission("wiki.ckcate.add")]
        [HttpPost]
        public ActionResult Add(AddCKCateInput modle)
        {            
            this.Service.Add(modle);
            return this.SuccessMsg("添加成功");
        }

        [Permission("wiki.ckcate.add")]
        [HttpPost]
        public ActionResult BatchAdd(string CateID,string Codes )
        {
            //this.Service.Add(modle);
            if(!string.IsNullOrEmpty(Codes)&&!string.IsNullOrEmpty(CateID))
            {
                List<CKCate> list = new List<CKCate>();
                Codes = Codes.TrimEnd(';');
                string[] arr = Codes.Split(';');
                foreach(var s in arr)
                {
                    list.Add(new CKCate { CateID = CateID, Code = s, CreateDate = DateTime.Now, IsExplort = 0, Id = Ace.IdStrategy.IdHelper.CreateStringSnowflakeId() });
                }
                this.Service.BatchInsert(list);
                return this.SuccessMsg("添加成功");
            }
            else
            {
                return this.FailedMsg();
            }
            
        }

        public IActionResult GetPTQRCode(string text, int pixel = 5)
        {
            string ProductValidUrl = Ace.Globals.Configuration["AppSettings:ProductValidUrl"];


            Response.ContentType = "image/jpeg";

            var bitmap = QRCoderHelper.GetPTQRCode(ProductValidUrl+text, pixel);
            MemoryStream ms = new MemoryStream();
            bitmap.Save(ms, ImageFormat.Jpeg);
            return File(ms.ToArray(), "image/png");
        }

        [HttpGet]
        public FileResult Export(string CateID) //FileStreamResult
        {
            //string sWebRootFolder = _hostingEnvironment.WebRootPath;
            string physicalFilePath = Directory.GetCurrentDirectory() + "\\" + Globals.Configuration["AppSettings:FileRootDir"] + "\\" + Globals.Configuration["AppSettings:UploadXls"];

            string sFileName = @"防伪码" + DateTime.Now.ToString("yyyy-MM-dd") + ".xlsx";
            //string URL = string.Format("{0}://{1}/{2}", Request.Scheme, Request.Host, sFileName);
            string FilePath = Path.Combine(physicalFilePath, sFileName);
            FileInfo file = new FileInfo(FilePath);
            if (file.Exists)
            {
                file.Delete();
                file = new FileInfo(FilePath);
            }

            List<CkCateInfo> list = this.CreateService<ICKCateService>().GetCKCateInfoList(CateID);

            using (ExcelPackage package = new ExcelPackage(file))
            {
                // add a new worksheet to the empty workbook
                ExcelWorksheet worksheet = package.Workbook.Worksheets.Add("防伪码");
                //First add the headers
 


                worksheet.Cells[1, 1].Value = "分类名称";
                worksheet.Cells[1, 2].Value = "防伪编码";
                 



                int m = 0;
                //Add values
                for (var i = 0; i < list.Count; i++)
                {
                    m = i + 2;

                    worksheet.Cells["A" + m].Value = list[i].CateName;
                    worksheet.Cells["B" + m].Value = list[i].Code;
                     
                }


                package.Save(); //Save the workbook.
            }
            //this.CreateService<ICKCateService>().UpdateExplort(CateID);
            return File(FilePath, "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet", "充值记录.xlsx"); //welcome.txt是客户端保存的名字
            //return File(new FileStream(FilePath, FileMode.Open), "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet", "防伪码.xlsx");
        }

    }
}